package top.fengyulou.xiaofeng.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import top.fengyulou.xiaofeng.common.Jr;
import top.fengyulou.xiaofeng.common.UserUtils;
import top.fengyulou.xiaofeng.common.WebUtils;
import top.fengyulou.xiaofeng.enums.ErrorCodeEnum;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 后台登录拦截器
 */
@Component
@Slf4j
public class AdminLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户数据
        JSONObject user = UserUtils.getUser(request);
        //用户未登录
        if (ObjectUtils.isEmpty(user)) {
            if (WebUtils.isAjax(request)) {
//                response.setContentType("text/html;charset=utf-8");
                response.setContentType("application/json");
                response.getWriter().print(JSONObject.toJSON(Jr.no(ErrorCodeEnum.NOT_LOGIN.getCode(), ErrorCodeEnum.NOT_LOGIN.getDesc())));
            } else {
                response.sendRedirect("/admin/login");
            }
            return false;
        }
        //用户已登录
        else {
            String type = user.getString("type");
            //普通用户
            if (type.equals("B")) {
                //跳转前台
                response.sendRedirect("/");
                return false;
            }
        }
        return true;
    }
}
